package com.jeesite.modules.wxrobot.socketHandle;

import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.utils.UserUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.adapter.standard.StandardWebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

@Service
public class QrCodeWebSocketHandler extends TextWebSocketHandler {
    //在线用户列表
    private static final Map<String, WebSocketSession> users;

    static {
        users = new HashMap<>();
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("成功建立连接");
        String name = getUser(session);
        if (StringUtils.isNotBlank(name)) {
            users.put(name, session);
            //session.sendMessage(new TextMessage("成功建立socket连接"));
        }
    }

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) {
        // ...
    }


    /**
     * 发送二维码
     * @param name
     * @param qrPath
     * @return
     */
    public boolean sendQrCode(String name, String qrPath) {
        if (users.get(name) == null) return false;
        WebSocketSession session = users.get(name);
        System.out.println("发送登陆二维码:" + session);
        if (!session.isOpen()) return false;
        try {
            session.sendMessage(new TextMessage(qrPath));
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if (session.isOpen()) {
            session.close();
        }
        System.out.println("连接出错");
        users.remove(getUser(session));
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("连接已关闭：" + status);
        users.remove(getUser(session));
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }


    /**
     * 获取在线用户信息
     * @param session
     * @return
     */
    private String getUser(WebSocketSession session) {
        try {
            StandardWebSocketSession sws = (StandardWebSocketSession)session;
            Principal principal = sws.getPrincipal();
            String name = principal.getName();
            return name;
        } catch (Exception e) {
            return null;
        }
    }
}
